package com.zxg.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @author HangDing
 *
 *         2014年1月1日
 */
public class SignUtil {

  private static final Logger log = LoggerFactory.getLogger(SignUtil.class);

  public static String sign(String parameter, String secret) {

    // 对参数+密钥做MD5运算
    MessageDigest md = null;
    byte[] digest = null;
    try {
      md = MessageDigest.getInstance("MD5");
      digest = md.digest((parameter + secret).getBytes("utf8"));
    } catch (NoSuchAlgorithmException e) {
      log.error(e.getMessage(), e);
      digest = (parameter + secret).getBytes();
    } catch (UnsupportedEncodingException e) {
      log.error(e.getMessage(), e);
      digest = (parameter + secret).getBytes();
    }
    // 转为16进制
    return byte2hex(digest);
  }

  private static String byte2hex(byte[] bytes) {
    StringBuilder sign = new StringBuilder();
    for (int i = 0; i < bytes.length; i++) {
      String hex = Integer.toHexString(bytes[i] & 0xFF);
      if (hex.length() == 1) {
        sign.append("0");
      }
      sign.append(hex.toUpperCase());
    }
    return sign.toString();
  }

}
